package me.zhengjie.modules.zhihu.visit.task;


import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Console;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.config.ApplicationContextProvider;
import me.zhengjie.modules.zhihu.common.ListUtils;
import me.zhengjie.modules.zhihu.question.domain.ZhihuQuestion;
import me.zhengjie.modules.zhihu.question.repository.ZhihuQuestionRepository;
import me.zhengjie.modules.zhihu.question.service.ZhihuQuestionService;
import me.zhengjie.modules.zhihu.question.service.dto.ZhihuQuestionDto;
import me.zhengjie.modules.zhihu.question.service.dto.ZhihuQuestionQueryCriteria;
import me.zhengjie.modules.zhihu.question.service.impl.ZhihuQuestionServiceImpl;
import me.zhengjie.modules.zhihu.theme.service.ZhThemeService;
import me.zhengjie.modules.zhihu.theme.service.dto.ZhThemeDto;
import me.zhengjie.modules.zhihu.theme.service.dto.ZhThemeQueryCriteria;
import me.zhengjie.modules.zhihu.visit.callable.VisitNumCallable;
import me.zhengjie.modules.zhihu.visit.domain.ZhQuestionVisit;
import me.zhengjie.modules.zhihu.visit.repository.ZhQuestionVisitRepository;
import me.zhengjie.modules.zhihu.visit.service.ZhQuestionVisitService;
import me.zhengjie.pool.excutor.CustomExecutorService;
import me.zhengjie.pool.ipproxy.domain.IPInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Slf4j
@Component
public class CalcVisitNumTask {

    static ZhQuestionVisitRepository zhQuestionVisitRepository = ApplicationContextProvider.getBean(ZhQuestionVisitRepository.class);
    static ZhihuQuestionRepository zhihuQuestionRepository = ApplicationContextProvider.getBean(ZhihuQuestionRepository.class);
    static ZhihuQuestionService hihuQuestionService = ApplicationContextProvider.getBean(ZhihuQuestionService.class);
    static ZhThemeService zhThemeService = ApplicationContextProvider.getBean(ZhThemeService.class);
    @Autowired
    private RedisTemplate redisTemplate;
    private static final int GROUP_SIZE = 200;

    private static DateTimeFormatter formatter= DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public CalcVisitNumTask() {
    }

    public String calc() throws Exception {
        List<String> range = redisTemplate.opsForList().range("ip", 0, -1);

        LocalDateTime date=LocalDateTime.now();
        AtomicInteger count = new AtomicInteger(0);
        List<ZhQuestionVisit> visits = new ArrayList<>();
        Timestamp timestamp = new Timestamp((new Date()).getTime());
        ZhThemeQueryCriteria criteria = new ZhThemeQueryCriteria();
        List<ZhThemeDto> zhThemeDtos = zhThemeService.queryAll(criteria);
        List<String> allQuestionId = new ArrayList<>();
        zhThemeDtos.forEach(zhThemeDto -> {
            List<String> questions = this.zhihuQuestionRepository.findByVisitDate(date.format(formatter),zhThemeDto.getId());
            //if (questions.size() == 0)
            allQuestionId.addAll(questions);
        });

        List<List<String>> groupList = new ArrayList<>();

        if (allQuestionId.size() == 0) return "总计主题："+zhThemeDtos.size()+"个，需刷新浏览量问题："+allQuestionId.size()+"个,"+"成功刷新浏览量问题："+count+"个";;
        if (allQuestionId.size() > 0 && allQuestionId.size() < 200) {
            groupList.add(allQuestionId);
        } else {
            groupList = ListUtils.partition(allQuestionId, GROUP_SIZE);
        }
        ExecutorService es = Executors.newFixedThreadPool(8);

        List<Future> futures = new ArrayList<>();
        for (List<String> ids : groupList) {
            //List<String> ids = questionList.stream().map(ZhihuQuestionDto::getId).collect(Collectors.toList());
            VisitNumCallable visitNumCallable = new VisitNumCallable(ids, count);
            futures.add(es.submit(visitNumCallable));
        }

//        futures.forEach(future -> {
//            try {
//                visits.addAll((List)future.get());
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            } catch (ExecutionException e) {
//                e.printStackTrace();
//            }
//        });
//
//        List<List<ZhQuestionVisit>> zhQuestionVisits = new ArrayList();
//        if (visits.size() > 0 && visits.size() < 200) {
//            (zhQuestionVisits).add(visits);
//        } else {
//            zhQuestionVisits = ListUtil.partition(visits, GROUP_SIZE);
//        }
//
//        Iterator var14 = ((List)zhQuestionVisits).iterator();
//
//        while(var14.hasNext()) {
//            List<ZhQuestionVisit> zhQuestionVisit = (List)var14.next();
//            this.questionVisitMapper.batchIsertQuestionVisit(zhQuestionVisit);
//        }

        es.shutdown();
        Console.log("恭喜你，全部转换完成，当前线程池已关闭：{},成功转化总计{}条", new Object[]{Thread.currentThread().getName(), count.addAndGet(1)-1});
        return "总计主题："+zhThemeDtos.size()+"个，需刷新浏览量问题："+allQuestionId.size()+"个,"+"成功刷新浏览量问题："+count+"个";
    }
}
